package basics;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import matrix_operations.Matrix;

public abstract class FileManager {

	public static String[] read(String path) throws IOException {
		ArrayList<String> strings = new ArrayList<String>();
		String[] returnStrings;
		BufferedReader br;

		br = new BufferedReader(new FileReader(path));
		while (br.ready()) {
			strings.add(br.readLine());
		}

		returnStrings = new String[strings.size()];
		for (int i = 0; i < strings.size(); i++) {
			returnStrings[i] = strings.get(i);
		}

		br.close();

		return returnStrings;
	}

	public static void write(String path, String string) throws IOException {

		BufferedWriter bw;

		bw = new BufferedWriter(new FileWriter(path));
		bw.write(string);
		bw.close();
	}

	public static Matrix readMatrix(String path) throws IOException {
		Matrix M = null;
		String[][] matrix;
		String[] lines = FileManager.read(path);

		int n = lines.length;
		int m = 0;

		matrix = new String[n][];

		for (int i = 0; i < n; i++) {
			matrix[i] = lines[i].split("\t");

			// defines m as the grater length of columns
			if (matrix[i].length > m)
				m = matrix[i].length;
		}

		M = new Matrix(n, m);

		for (int i = 0; i < M.getN(); i++) {
			for (int j = 0; j < M.getM(); j++) {
				try {
					M.setValue(i, j, Double.parseDouble(matrix[i][j]));
				} catch (Exception e) {
					M.setValue(i, j, 0);
				}
			}
		}
		return M;
	}

	public static void write(Matrix M, String path) throws IOException {
		StringBuilder stringBuilder = new StringBuilder();
		String s = "";

		for (int i = 0; i < M.getN(); i++) {
			s = "";
			for (int j = 0; j < M.getM(); j++) {
				s += M.getValue(i, j) + "\t";
			}
			stringBuilder.append(s + "\n");
		}

		FileManager.write(path, stringBuilder.toString());
	}
}
